/**
    * Created by Edwin on 2015/12/17 0017.
    */
var rippleApp = angular.module('adminApp',[]);

rippleApp.factory('pageData',function(){
    return {
        bigCategory : $("#currentCate").val()
    }
});

rippleApp.factory('getItemService',['$http',function($http){
    //获取单个对象信息
    var getItemRequest = function(currentPage,targetId){
        var requestPath = "/admin/manage/"+currentPage+"/item?uid="+targetId;
        return $http.get(requestPath)
    };
    return {
        itemInfo : function(currentPage,targetId){
            return getItemRequest(currentPage,targetId);
        }
    }
}]);

//材料列表
rippleApp.controller('ingredientList',['$scope','$http','pageData','getItemService',function($scope,$http,pageData,getItemService){
    $scope.formData = {};
    //获取材料列表信息
    initPagination($scope,$http);
    //删除文档
    initDelOption($scope,$http,'您确认要删除选中的文档吗？');
    //添加或修改
    $scope.mdfFun=function(id){
        $scope.targetID=id;
        $('#mdfIngrendient').modal('show');
        if(id){
            getItemService.itemInfo(pageData.bigCategory,id).success(function(result){
                $scope.formData.name = result.name;
                $scope.formData.type = result.type;
                $scope.formData.price = result.price;
                $("#ingredientName").val($scope.formData.name);
                $("#ingredientType").val($scope.formData.type);
                $("#ingredientPrice").val($scope.formData.price);
            })
        }else{
            $scope.formData.name ="";
            $scope.formData.type="0";
            $scope.formData.price = "0";

            $("#ingredientName").val($scope.formData.name);
            $("#ingredientType").val($scope.formData.type);
            $("#ingredientPrice").val($scope.formData.price);
        }

    }
    $('#mdfIngrendient').on('show.bs.modal', function (event) {
    }).on('hide.bs.modal', function (event) {
        $scope.targetID="";
    });
    $scope.processForm = function(isValid){
        $scope.formData.name =$("#ingredientName").val();
        $scope.formData.type=$("#ingredientType").val();
        $scope.formData.price = $("#ingredientPrice").val();
        angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data){
            initPagination($scope,$http);
        });
    };
}]);

//菜式列表
rippleApp.controller('cuisinetList',['$scope','$http','pageData','getItemService',function($scope,$http,pageData,getItemService){
    $scope.formData = {};
    //获取材料列表信息
    initPagination($scope,$http);
    //删除文档
    initDelOption($scope,$http,'您确认要删除选中的文档吗？');
    //添加或修改
    $scope.mdfFun=function(id){
        $scope.targetID=id;
        $('#mdfDiv').modal('show');
        if(id){
            getItemService.itemInfo(pageData.bigCategory,id).success(function(result){
                $(".datatr").remove();
                $scope.formData.name = result.name;
                $scope.formData.type = result.type;
                $("#cuisineName").val($scope.formData.name);
                $("#cuisineType").val($scope.formData.type);

                for(var i in result.productionMaterias){
                    var obj=result.productionMaterias[i];
                    addPurchaseItem(obj.id, obj.name,"1",obj.dj ,obj.unit,obj.sl);
                }

            })
        }

    }
    $('#mdfDiv').on('show.bs.modal', function (event) {
    }).on('hide.bs.modal', function (event) {
        $("#nope").val("");
        $scope.targetID="";
        $scope.formData.name = "";
        $scope.formData.type = 0;
        $("#cuisineName").val($scope.formData.name);
        $("#cuisineType").val($scope.formData.type);
        $(".datatr").remove();
        priceSyn($("#cart"));
    });
    $scope.processForm = function(isValid){
        var productionMaterias = [];
        $("#cart .datatr").each(function() {
            var productionMateria = {};
            var ingId = $(this).attr("ingId");
            var ingname = $(this).attr("ingname");
            var ingtype = $(this).attr("ingtype");
            var sl = $(this).find(".sl").val();
            var dj = $(this).find(".dj").html();
            var unit = $(this).find(".unit").val();
            productionMateria["id"] = ingId;
            productionMateria["name"] = ingname;
            productionMateria["type"] = ingtype;
            productionMateria["sl"] = sl;
            productionMateria["dj"] = dj;
            productionMateria["zj"] = (sl * dj).toFixed(2);
            productionMateria["unit"] = unit;
            productionMaterias.push(productionMateria);
        });
        $scope.formData.productionMaterias=productionMaterias;
        $scope.formData.name=$("#cuisineName").val();
        $scope.formData.type=$("#cuisineType").val();
        angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data){
            initPagination($scope,$http);
            $(".datatr").remove();
            $("#cuisineName").val("");
            $("#cuisineType").val(0);
        });
    };

    $("#cart").on('input propertychange', 'tr .sl', function() {
        priceSyn($(this).parent().parent());
    });

    $("#cart").on('blur', 'tr .dj', function() {
        priceSyn($(this).parent().parent());
    });

    $http.get("/admin/manage/getDocumentList/ingredient?limit=1000&currentPage=1").success(function(result){
        var cailiao=[];
        for(var i in result.docs){
            var t={};
            t["hex"]="#EFDECD";
            t["label"]=result.docs[i].name;
            t["id"]=result.docs[i]._id;
            t["sx"]=result.docs[i].sx;
            t["name"]=result.docs[i].name;
            t["rgb"]="(239, 222, 205)";
            cailiao.push(t);
        }
        $('#nope').autocompleter({
            // marker for autocomplete matches
            highlightMatches: true,

            // object to local or url to remote search
            source: cailiao,

            // custom template
            template: '{{ name }}',

            // show hint
            hint: true,

            // abort source if empty field
            empty: false,

            // max results
            limit: 5,

            callback: function (value, index, selected) {
                if (selected) {
                    $("#nope").val("");
                    addPurchaseItem(selected.id, selected.name, "1", "1", "斤","1");
                }
            }
        });
    });

}]);

//套餐列表
rippleApp.controller('setmealList',['$scope','$http','pageData','getItemService',function($scope,$http,pageData,getItemService){
    $scope.formData = {};
    //获取材料列表信息
    initPagination($scope,$http);
    //删除文档
    initDelOption($scope,$http,'您确认要删除选中的文档吗？');
    //添加或修改
    $scope.mdfFun=function(id){
        $scope.targetID=id;
        $('#mdfDiv').modal('show');
        if(id){
            getItemService.itemInfo(pageData.bigCategory,id).success(function(result){
                $(".datatr").remove();
                $scope.formData.name = result.name;
                $scope.formData.price = result.price;
                $("#setmealName").val($scope.formData.name);
                $("#setmealPrice").val($scope.formData.price);

                for(var i in result.items){
                    var obj=result.items[i];
                    addPurchaseItem(obj.id, obj.name,obj.price);
                }

            })
        }

    }
    $('#mdfDiv').on('show.bs.modal', function (event) {
    }).on('hide.bs.modal', function (event) {
        $("#nope").val("");
        $scope.targetID="";
        $scope.formData.name = "";
        $scope.formData.price = 0;
        $("#setmealName").val($scope.formData.name);
        $("#setmealPrice").val($scope.formData.type);
        $(".datatr").remove();
        priceSyn($("#cart"));
    });
    $scope.processForm = function(isValid){
        var items = [];
        $("#cart .datatr").each(function() {
            var ingId = $(this).attr("csId");
            items.push(ingId);
        });
        $scope.formData.items=items;
        $scope.formData.name=$("#setmealName").val();
        $scope.formData.price=$("#setmealPrice").val();
        angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data){
            initPagination($scope,$http);
            $(".datatr").remove();
            $("#setmealName").val("");
            $("#setmealPrice").val(0);
        });
    };


    $http.get("/admin/manage/getDocumentList/cuisine?limit=1000&currentPage=1").success(function(result){
        var cailiao=[];
        for(var i in result.docs){
            var t={};
            t["hex"]="#EFDECD";
            t["label"]=result.docs[i].name;
            t["id"]=result.docs[i]._id;
            t["sx"]=result.docs[i].sx;
            t["name"]=result.docs[i].name;
            t["price"]=result.docs[i].price;
            t["rgb"]="(239, 222, 205)";
            cailiao.push(t);
        }
        $('#nope').autocompleter({
            // marker for autocomplete matches
            highlightMatches: true,

            // object to local or url to remote search
            source: cailiao,

            // custom template
            template: '{{ name }}',

            // show hint
            hint: true,

            // abort source if empty field
            empty: false,

            // max results
            limit: 5,

            callback: function (value, index, selected) {
                if (selected) {
                    $("#nope").val("");
                    addPurchaseItem(selected.id, selected.name,selected.price);
                }
            }
        });
    });

}]);

//进货管理
rippleApp.controller('purchaseList',['$scope','$http','pageData','getItemService',function($scope,$http,pageData,getItemService){
    $scope.formData = {};
    $scope.formData.name="";
    initPagination($scope,$http);
    initDelOption($scope,$http,'您确认要删除选中的文档吗？');
    $scope.mdfFun=function(id){
        $scope.targetID=id;
        $('#mdfDiv').modal('show');
        $("#nope").val("");
        $scope.targetID="";
        $scope.formData.name = "";
        $(".datatr").remove();
        priceSyn($("#cart"));
        if(id){
            getItemService.itemInfo(pageData.bigCategory,id).success(function(result){
                $(".datatr").remove();
                $scope.formData.name = result.name;
                $scope.formData.time =  new Date(result.time).Format('yyyy-MM-dd hh:mm');
                for(var i in result.items){
                    var obj=result.items[i];
                    addPurchaseItem(obj.ing._id, obj.ing.name,obj.dj,obj.sl);
                }
                //$(".viewSty").hide();
               // $(".banSty").attr("disabled",true);
            })
        }else{
            $scope.formData.time =  new Date().Format('yyyy-MM-dd hh:mm');
            //$(".viewSty").show();
            //$(".banSty").attr("disabled",false);

        }

    }
    $('#mdfDiv').on('show.bs.modal', function (event) {
    }).on('hide.bs.modal', function (event) {

    });
    $scope.processForm = function(isValid){
        var items = [];
        var total=0;
        $("#cart .datatr").each(function() {
            var item={};
            var ingId = $(this).attr("ingId");
            var ingname = $(this).attr("ingname");
            var sl = $(this).find(".sl").val();
            var dj = $(this).find(".dj").html();
            item["ing"] = ingId;
            item["name"] = ingname;
            item["sl"] = sl;
            item["dj"] = dj;
            item["zj"] = (sl * dj).toFixed(2);
            items.push(item);
            total=total+sl * dj;
        });
        $scope.formData.price=total;
        $scope.formData.items=items;
        angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data){
            if(!$scope.formData.targetID) {
                for (var i in items) {
                    var uData = {};
                    uData["price"]=items[i].dj;
                    uData["ig"]=items[i].ing;
                    angularHttpPost($http, isValid, "/admin/manage/ingbuyrecord/addOne", uData);
                    angularHttpPost($http, isValid, "/admin/manage/ingredient/modify?uid="+items[i].ing, uData);
                }

                var uData={};
                uData["price"]=-total;
                uData["type"]=1;
                uData["pid"]=data._id;
                angularHttpPost($http, isValid, "/admin/manage/cashflow/addOne", uData);


            }
            initPagination($scope, $http);
            $(".datatr").remove();
            $scope.formData.name = "";
        });
    };

    $("#cart").on('input propertychange', 'tr .sl', function() {
        priceSyn($(this).parent().parent());
    });

    $("#cart").on('blur', 'tr .dj', function() {
        priceSyn($(this).parent().parent());
    });


    $http.get("/admin/manage/getDocumentList/ingredient?limit=1000&currentPage=1").success(function(result){
        var cailiao=[];
        for(var i in result.docs){
            var t={};
            t["hex"]="#EFDECD";
            t["label"]=result.docs[i].name;
            t["id"]=result.docs[i]._id;
            t["sx"]=result.docs[i].sx;
            t["name"]=result.docs[i].name;
            t["price"]=result.docs[i].price;
            t["rgb"]="(239, 222, 205)";
            cailiao.push(t);
        }
        $('#nope').autocompleter({
            highlightMatches: true,

            // object to local or url to remote search
            source: cailiao,

            // custom template
            template: '{{ name }}',

            // show hint
            hint: true,

            // abort source if empty field
            empty: false,

            // max results
            limit: 5,

            callback: function (value, index, selected) {
                if (selected) {
                    $("#nope").val("");
                    addPurchaseItem(selected.id, selected.name,selected.price,1);
                }
            }
        });
    });

}]);

//销售管理
rippleApp.controller('saleList',['$scope','$http','pageData','getItemService',function($scope,$http,pageData,getItemService){
    $scope.formData = {};
    $scope.formData.name="";
    //获取材料列表信息
    initPagination($scope,$http);
    //删除文档
    initDelOption($scope,$http,'您确认要删除选中的文档吗？');
    //添加或修改
    $scope.mdfFun=function(id){
        $scope.targetID=id;
        $("#dataLoading").removeClass("hide");
        if(id){
            getItemService.itemInfo(pageData.bigCategory,id).success(function(result){
                $(".datatr").remove();
                $scope.formData.name = result.name;
                for(var i in result.items){
                    var obj=result.items[i];
                    addPurchaseItem(obj._id, obj.name,obj.dj,obj.sl);
                }
                $("#dataLoading").addClass("hide");
                $('#mdfDiv').modal('show');

            })
        }else{
            $('#mdfDiv').modal('show');
        }

    }
    $('#mdfDiv').on('show.bs.modal', function (event) {
    }).on('hide.bs.modal', function (event) {
        $("#nope").val("");
        $scope.targetID="";
        $scope.formData.name = "";
        $(".datatr").remove();
        priceSyn($("#cart"));
    });
    $scope.processForm = function(isValid){
        var items = [];
        var total=0;
        $("#cart .datatr").each(function() {
            var item={};
            var ingId = $(this).attr("ingId");
            var ingname = $(this).attr("ingname");
            var sl = $(this).find(".sl").val();
            var dj = $(this).find(".dj").html();
            item["ing"] = ingId;
            item["name"] = ingname;
            item["sl"] = sl;
            item["dj"] = dj;
            item["zj"] = (sl * dj).toFixed(2);
            items.push(item);
            total=total+sl * dj;
        });
        $scope.formData.price=total;
        $scope.formData.items=items;
        angularHttpPost($http,isValid,getTargetPostUrl($scope,pageData.bigCategory),$scope.formData,function(data){
            if(!$scope.formData.targetID) {
                for (var i in items) {
                    var uData = {};
                    uData["price"]=items[i].dj;
                    uData["ig"]=items[i].ing;
                    angularHttpPost($http, isValid, "/admin/manage/ingbuyrecord/addOne", uData);
                    angularHttpPost($http, isValid, "/admin/manage/ingredient/modify?uid="+items[i].ing, uData);
                }

                var uData={};
                uData["price"]=total;
                uData["type"]=1;
                uData["pid"]=data._id;
                angularHttpPost($http, isValid, "/admin/manage/cashflow/addOne", uData);


            }
            initPagination($scope, $http);
            $(".datatr").remove();
            $scope.formData.name = "";
        });
    };

    $("#cart").on('input propertychange', 'tr .sl', function() {
        priceSyn($(this).parent().parent());
    });

    $("#cart").on('blur', 'tr .dj', function() {
        priceSyn($(this).parent().parent());
    });


    $http.get("/admin/manage/getDocumentList/setmeal?limit=1000&currentPage=1").success(function(result){
        var cailiao=[];
        for(var i in result.docs){
            var t={};
            t["hex"]="#EFDECD";
            t["label"]=result.docs[i].name;
            t["id"]=result.docs[i]._id;
            t["sx"]=result.docs[i].sx;
            t["name"]=result.docs[i].name;
            t["price"]=result.docs[i].price;
            t["rgb"]="(239, 222, 205)";
            cailiao.push(t);
        }
        $('#nope').autocompleter({
            highlightMatches: true,

            // object to local or url to remote search
            source: cailiao,

            // custom template
            template: '{{ name }}',

            // show hint
            hint: true,

            // abort source if empty field
            empty: false,

            // max results
            limit: 5,

            callback: function (value, index, selected) {
                if (selected) {
                    $("#nope").val("");
                    addPurchaseItem(selected.id, selected.name,selected.price,1);
                }
            }
        });
    });

}]);

//资金流动
rippleApp.controller('cashFlowList',['$scope','$http','pageData','getItemService',function($scope,$http,pageData,getItemService){
    $scope.cmode=0;
    $scope.formData = {};
    $scope.formData.name="";
    $scope.formData.cashFlowType="0";
    initPagination($scope,$http);
    initDelOption($scope,$http,'您确认要删除选中的文档吗？');
    $scope.switchCashType=function(){
        swithCashType($scope,$http,1,$scope.formData.cashFlowType);
    };
    $scope.addOther=function(){
        addOtherItem($scope.formData.cashFlowType);
        $("#nope").val("");
    };
    $scope.changeMode=function(){
        if($("#cmode").hasClass("tRed")){
            $("#cmode").removeClass("tRed");
            $scope.cmode=0;
        }else{
            $("#cmode").addClass("tRed");
            $scope.cmode=1;
        }
    };
    $scope.mdfFun=function(id){
        //根据类型加载自动填充数据
        $("#nope").val("");
        $scope.targetID="";
        $(".datatr").remove();
        priceSyn($("#cart"));
        $("#dataLoading").removeClass("hide");
        if(id){
            getItemService.itemInfo(pageData.bigCategory,id).success(function(result){
                $scope.formData.name = result.name;
                $scope.formData.time =  new Date(result.time).Format('yyyy-MM-dd hh:mm');
                $scope.formData.cashFlowType=result.type+"";
                $scope.targetID=result._id;
                swithCashType($scope,$http,id,$scope.formData.cashFlowType);
                for(var i in result.items){
                    var obj=result.items[i];
                    addPurchaseItem(obj.id, obj.name,obj.price,obj.sl,$scope.formData.cashFlowType);
                }
                $("#dataLoading").addClass("hide");
                $('#mdfDiv').modal('show');

            })
        }else{
            $scope.formData.cashFlowType="0";
            $scope.formData.name =$scope.formData.name!=null&&$scope.formData.name!=""?"": $scope.formData.name;
            $scope.formData.time =  new Date().Format('yyyy-MM-dd hh:mm');
            swithCashType($scope,$http,id,$scope.formData.cashFlowType);
            $("#dataLoading").addClass("hide");
            $('#mdfDiv').modal('show');
        }

    }
    $scope.processForm = function(isValid){
        saveCashFlow($scope,$http,pageData,isValid);
    };

    $("#cart").on('input propertychange', 'tr .sl', function() {
        priceSyn($(this).parent().parent());
    });

    $("#cart").on('blur', 'tr .dj', function() {
        priceSyn($(this).parent().parent());
    });

    $('.form_date').datetimepicker({
        language:  'zh-CN',
        weekStart: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2
    });

    $('.form_date')
        .datetimepicker()
        .on('changeDate', function(ev,date){
            $(this).find(".dateVal").val(ev.date.Format("yyyy-MM-dd"));
            $(this).find("span").html(ev.date.Format("yyyy-MM-dd"));
            $scope.startDate=$("#startDate").val();
            $scope.endtDate=$("#endDate").val();
            $("#searchForm").submit();
     });


    $("#serchBtn").click(function(){
        getPageInfos($scope,$http,"/admin/manage/getDocumentList/cashflow",'normalList');
    })



}]);


